<template>
  <div class="body" @keyup.enter="saveFn">
    <div class="body-con">
      <div class="body-con-cen">
        <div class="body-con-cen-box">
          <div class="body-con-cen-box-bg"></div>
          <div class="body-con-cen-box-tabs" v-if="setPwdVisible">
            <ul>
              <li class="selected" style="width: 100%;">
                <div>设置登录密码</div>
              </li>
              <div class="tabs-bar" :style="`left: 137px;transition: 0.5s;`"></div>
            </ul>
            <form class="body-con-cen-box-form">
              <div class="body-con-cen-box-form-item">
                <div class="body-con-cen-box-form-item-inline">
                  <input class="body-con-cen-box-form-item-inline-input" :type="pwdVisible ? 'text' : 'password'"
                    v-model="saveForm.password" placeholder="请输入密码" />
                  <el-icon class="icon-view" :size="20" color="#555" @click="pwdVisible = !pwdVisible">
                    <template v-if="pwdVisible">
                      <View />
                    </template>
                    <template v-else>
                      <Hide />
                    </template>
                  </el-icon>
                </div>
                <div class="body-con-cen-box-form-item-inline">
                  <input class="body-con-cen-box-form-item-inline-input" :type="rePwdVisible ? 'text' : 'password'"
                    v-model="repassword" placeholder="请再次确认密码" />
                  <el-icon class="icon-view" :size="20" color="#555" @click="rePwdVisible = !rePwdVisible">
                    <template v-if="rePwdVisible">
                      <View />
                    </template>
                    <template v-else>
                      <Hide />
                    </template>
                  </el-icon>
                </div>
                <div class="body-con-cen-box-form-item forgotpwd">
                  <div class="label"></div>
                  <button class="link" type="button" @click="tabsIndex = 0;setPwdVisible = !setPwdVisible">返回密码登录</button>
                </div>
                <div class="body-con-cen-box-form-login" type="button" :disabled="saveDisabled" @click="setPwdFn">登录</div>
                <div class="body-con-cen-box-form-home">
                  <a href="/">进入技考邦 - 练题平台</a>
                </div>
              </div>
            </form>
          </div>
          <div class="body-con-cen-box-tabs" v-else>
            <ul>
              <li :class="tabsIndex === 0 ? 'selected' : ''" @click="tabsIndex = 0">
                <div>账号密码登录</div>
              </li>
              <li :class="tabsIndex === 1 ? 'selected' : ''" @click="tabsIndex = 1">
                <div>短信验证码登录</div>
              </li>
              <div class="tabs-bar" :style="`left: ${tabsIndex === 0 ? '58px' : '215px'};transition: 0.5s;`"></div>
            </ul>
            <form class="body-con-cen-box-form">
              <div class="body-con-cen-box-form-item">
                <div class="body-con-cen-box-form-item-inline">
                  <input class="body-con-cen-box-form-item-inline-input" type="text" maxlength="11"
                    v-model="saveForm.phoneNo" placeholder="请输入手机号" />
                </div>
                <div class="body-con-cen-box-form-item-inline" v-if="tabsIndex === 0">
                  <input class="body-con-cen-box-form-item-inline-input" :type="pwdVisible ? 'text' : 'password'"
                    v-model="saveForm.password" placeholder="请输入密码" />
                  <el-icon class="icon-view" :size="20" color="#555" @click="pwdVisible = !pwdVisible">
                    <template v-if="pwdVisible">
                      <View />
                    </template>
                    <template v-else>
                      <Hide />
                    </template>
                  </el-icon>
                </div>
                <div class="body-con-cen-box-form-item-inline" v-else>
                  <input class="body-con-cen-box-form-item-inline-input" type="text" v-model="saveForm.phoneCode"
                    placeholder="请输入验证码" />
                  <button class="btn-code" type="button" :disabled="codeDisabled" @click="getCodeFn">{{ codeText
                  }}</button>
                </div>
                <div class="body-con-cen-box-form-item forgotpwd">
                  <div class="label">
                    <el-checkbox label="记住手机号及密码" v-model="remember" v-show="tabsIndex === 0" />
                  </div>
                  <button class="link" type="button" @click="forgotpwdFn">忘记密码</button>
                </div>
                <div class="body-con-cen-box-form-login" type="button" :disabled="saveDisabled" @click="saveFn">登录</div>
                <div class="body-con-cen-box-form-home">
                  <a href="/">进入技考邦 - 练题平台</a>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { reactive, ref, getCurrentInstance, watch } from 'vue';
import { View, Hide } from '@element-plus/icons-vue';
import { regPhone } from '@/utils/util';
import { useRouter } from 'vue-router';
const { $api } = getCurrentInstance().appContext.config.globalProperties;
const router = useRouter()
const saveForm = reactive({
  phoneNo: localStorage.getItem('phoneNo') || '',
  password: localStorage.getItem('password') || '',
  phoneCode: ''
})
const tabsIndex = ref(0)
const pwdVisible = ref(false)
const rePwdVisible = ref(false)
const codeText = ref('获取验证码')
const codeDisabled = ref(true)
const saveDisabled = ref(false)
const codeInter = ref(null)
const remember = ref(localStorage.getItem('phoneNo') && localStorage.getItem('password') ? true : false)
const setPwdVisible = ref(false)
const repassword = ref('')

// 清除计时器
clearInterval(codeInter.value)
codeInter.value = null;
// 监听
watch([() => saveForm.phoneNo, () => tabsIndex.value], ([phoneVal, tabsVal]) => {
  codeDisabled.value = !regPhone.test(phoneVal);
  if (tabsVal === 1) {
    // 清除计时器
    clearInterval(codeInter.value)
    codeInter.value = null;
    downTimeFn()
  }
})
// 忘记密码
const forgotpwdFn = () => {
  ElMessageBox.confirm('请联系工作人员：0818-2282222', '系统提示', {
    showClose: false,
    showCancelButton: false,
    showConfirmButton: false
  }).catch(() => { })
}
// 获取验证码
const getCodeFn = async () => {
  if (saveForm.phoneNo == '') {
    ElMessage.warning('请输入手机号');
    return false;
  }
  if (!regPhone.test(saveForm.phoneNo)) {
    ElMessage.warning('手机号格式有误');
    return false;
  }
  $api.sendPhoneCodeApi({
    phone: saveForm.phoneNo
  }).then((res) => {
    if (res.errno === 0) {
      codeDisabled.value = true;
      localStorage.setItem('t', 60)
      downTimeFn()
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
// 获取验证码倒计时
const downTimeFn = () => {
  if (localStorage.getItem('t')) {
    codeDisabled.value = true;
    let t = Number(localStorage.getItem('t'));
    codeText.value = `重新发送（${t}s）`;
    codeInter.value = setInterval(() => {
      if (t < 1) {
        clearInterval(codeInter.value)
        codeInter.value = null;
        codeText.value = '获取验证码';
        codeDisabled.value = !regPhone.test(saveForm.phoneNo) ? true : false;
        localStorage.removeItem('t')
        return false;
      }
      t--;
      localStorage.setItem('t', t)
      codeText.value = `重新发送（${t}s）`;
    }, 1000)
  }
}
// 密码登录
const saveFn = () => {
  if (saveForm.phoneNo == '') {
    ElMessage.warning('请输入手机号');
    return false;
  }
  if (tabsIndex.value === 0 && saveForm.password == '') {
    ElMessage.warning('请输入密码');
    return false;
  }
  saveDisabled.value = true;
  let _$api = $api.loginByPasswordApi;
  // 切换短信验证码登录接口
  if (tabsIndex.value === 1) {
    _$api = $api.loginByPhoneCodeApi;
  }
  _$api(saveForm).then((res) => {
    setTimeout(() => {
      saveDisabled.value = false;
    }, 1000)
    // 未设置密码
    if (res.errno === 130) {
      localStorage.setItem('token', res.result.token)
      setPwdVisible.value = true;
      return false;
    }
    if (res.errno === 0) {
      // 是否记住手机号，密码
      if (remember.value && tabsIndex.value === 0) {
        localStorage.setItem('phoneNo', saveForm.phoneNo)
        localStorage.setItem('password', saveForm.password)
      } else {
        localStorage.removeItem('phoneNo')
        localStorage.removeItem('password')
      }
      localStorage.setItem('token', res.result.token)
      router.replace('/')
      return false;
    }
    ElMessage.error(res.errmsg)
  }).catch((err) => {
    saveDisabled.value = false;
  })
}
// 设置密码
const setPwdFn = () => {
  if (saveForm.password !== repassword.value) {
    ElMessage.warning('密码不一致');
    return false;
  }
  $api.setPasswordApi({
    phoneNo: saveForm.phoneNo,
    password: saveForm.password,
    closeOnClickModal: false,
    closeOnPressEscape: false
  }).then((res) => {
    if (res.errno === 0) {
      ElMessage.success('设置密码成功')
      tabsIndex.value = 0;
      saveFn()
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
</script>

<style lang="scss" scoped>
.body {
  height: 100%;
  overflow: hidden;

  &-con {
    width: 100%;
    min-width: 800px;
    overflow: hidden;
    background: url(@/assets/img/login-bg.png) no-repeat;
    background-color: #f2f7ff;
    background-size: 100% 100%;
    min-height: 100vh;
    box-sizing: content-box;
    display: flex;
    display: -webkit-flex;
    flex-flow: column;

    &-cen {
      overflow: hidden;
      width: 1000px;

      &-box {
        width: 800px;
        height: 460px;
        background: #fff;
        box-shadow: 0 8px 32px 0 #b8d1f2;
        border-radius: 12px;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -400px;
        margin-top: -230px;
        z-index: 999;

        &-bg {
          width: 433px;
          height: 528px;
          position: absolute;
          background: url(@/assets/img/effect@1x.png);
          background-size: 100% 100%;
          top: -36px;
          left: -28px;
        }

        &-tabs {
          width: 370px;
          height: 348px;
          float: right;
          margin: 80px 30px 20px 0;

          >ul {
            list-style: none;
            padding: 0;
            width: 320px;
            margin: 0 auto;
            justify-content: space-around;
            position: relative;
            overflow: hidden;
            height: 45px;
            margin-bottom: 30px;

            >li {
              width: 160px;
              height: 46px;
              float: left;
              text-align: center;
              cursor: pointer;
              font-size: 18px;
              font-weight: 400;
              color: #333;

              &.selected {
                font-weight: 700;
                color: #FF9001;
              }
            }

            .tabs-bar {
              width: 44px;
              height: 15px;
              position: absolute;
              left: 58px;
              top: 30px;
              background: url(@/assets/img/bar@1x.png);
              background-size: 100% 100%;
              box-sizing: border-box;
              z-index: 1;
            }
          }
        }

        &-form {
          box-sizing: border-box;
          margin: 0;
          padding: 0;
          color: rgba(0, 0, 0, .85);
          font-size: 14px;
          font-variant: tabular-nums;
          line-height: 1.5715;
          list-style: none;
          font-feature-settings: "tnum", "tnum";

          &-item {
            width: 350px;
            margin: 0 auto;

            &-inline {
              width: 320px;
              height: 46px;
              margin: 0 auto 20px;
              background: #fff;
              margin: 0 auto 20px;
              background: #fff;
              position: relative;

              &-input {
                width: 320px;
                height: 46px;
                line-height: 46px;
                font-size: 16px;
                font-weight: 400;
                color: #333;
                background: none;
                padding-left: 15px;
                border-radius: 8px;
                border: 1px solid #e6e6e6;
                outline: none;
                box-sizing: border-box;
              }

              .icon-view {
                position: absolute;
                right: 14px;
                cursor: pointer;
                top: 12px;
              }

              .btn-code {
                position: absolute;
                top: 8px;
                right: 11px;
                font-size: 16px;
                font-weight: 400;
                background: transparent;
                color: #FF9001;

                &:disabled {
                  color: #B2B2B2;
                  cursor: no-drop;
                }
              }
            }

            &.forgotpwd {
              width: 313px;
              margin: 0 auto 9px;
              align-items: center;
              overflow: hidden;
              display: flex;
              justify-content: space-between;

              .label {
                height: 34px;
                line-height: 38px;
              }

              .link {
                color: #FF9001;
                border-color: transparent;
                background: transparent;
                box-shadow: none;
              }
            }
          }

          &-login {
            width: 340px;
            height: 66px;
            line-height: 52px;
            min-height: auto;
            padding: 0;
            margin: 0 auto;
            background: url(@/assets/img/btn-activity@2x.png) no-repeat;
            background-size: 100% 100%;
            cursor: pointer;
            text-align: center;
            font-size: 18px;
            font-weight: 400;
            color: #fff;
          }

          &-home {
            text-align: center;

            >a {
              color: #888;
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}
</style>